
#include <Ciao.h>
const String *socketserial = new String("socketserial");
class ML_DEPS : public Stream
{
    String income = "";
    unsigned int incomeIndex = 0;

  public:
    ML_DEPS()
    {
        SERIAL_PORT_IN_USE.setTimeout(1);
        Ciao.begin();
    }
    size_t print(const String str)
    {
        Ciao.write(*socketserial, str);
        return str.length();
    }
    size_t print(String *str)
    {
        Ciao.write(*socketserial, *str);
        return str->length();
    }
    size_t print(const char chs[])
    {
        String *s = new String(chs);
        Ciao.write(*socketserial, *s);
        return s->length();
    }
    size_t write(const uint8_t *buff, size_t size)
    {
        char chs[size + 1];
        //std::copy(buff, buff+size, chs);
        memcpy(chs, buff, size);
        chs[size] = '\n';
        String str = String(chs);
        return this->print(str);
    }
    size_t write(const char *str)
    {
        String *s = new String(str);
        Ciao.write(*socketserial, *s);
        return s->length();
    }

    size_t write(uint8_t o)
    {
        Ciao.write(*socketserial, (String((char)o)));
        return 1;
    }
    int read()
    {
        if (incomeIndex < income.length())
        {
            char ch = income.charAt(incomeIndex);
            incomeIndex++;
            return ch;
        }
        CiaoData data = Ciao.read(*socketserial);
        if (data.isEmpty())
        {
            return -1;
        }
        else
        {
            income = data.get(1);
            incomeIndex = 1;
            return income.charAt(0);
        }
    }

    int peek()
    {
        if (incomeIndex < income.length())
        {
            char ch = income.charAt(incomeIndex);
            return ch;
        }
        CiaoData data = Ciao.read(*socketserial);
        if (data.isEmpty())
        {
            return -1;
        }
        else
        {
            income = data.get(1);
            incomeIndex = 0;
            return income.charAt(0);
        }
    }
    int available()
    {
        if (incomeIndex < income.length())
        {
            int i = income.length() - incomeIndex;
            return i;
        }
        CiaoData data = Ciao.read(*socketserial);
        if (data.isEmpty())
        {
            return 0;
        }
        else
        {
            income = data.get(1);
            incomeIndex = 0;
            return income.length();
        }
    }
    void flush() {}
};
